package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.TreeNode;

/**
 * @Author fengye
 * @Date 2023/4/20 9:08
 **/
public class ValidateBinarySearchTree98 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(2, new TreeNode(1), new TreeNode(3));
        new ValidateBinarySearchTree98().isValidBST(root);
    }

    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean isValidBST(TreeNode node, long lower, long upper) {
        if (node == null) {
            return true;
        }
        if (node.val <= lower || node.val >= upper) {
            return false;
        }
        return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper);
    }

    public boolean isValidBST1(TreeNode root) {
        if(root == null) {
            return true;
        }
        boolean isValid = true;


        if(root.left != null) {
            if(root.left.val > root.val) {
                isValid = false;
            }
            isValid = isValidBST(root.left);
        }
        if(root.right != null) {
            if(root.right.val < root.val) {
                isValid = false;
            }
            isValid = isValidBST(root.right);

        }

        return isValid;
    }
}
